package com.shirotest.shiro;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import com.shirotest.utility.StringUtility;

/**
 * 自定义会话持久操作
 */
public class MyrSessionDAO extends AbstractSessionDAO {
	private static final Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();

	@Override
	public void update(Session session) throws UnknownSessionException {
		sessionMap.put(session.getId().toString(), session);
	}

	@Override
	public void delete(Session session) {
		sessionMap.remove(session.getId().toString());
	}

	@Override
	public Collection<Session> getActiveSessions() {
		Set<Session> collection = new HashSet<Session>();
		sessionMap.forEach((key,value) -> {
			collection.add(value);
		});
		return collection;
	}

	@Override
	protected Serializable doCreate(Session session) {
		String sessionId = StringUtility.getUUID();
		((SimpleSession) session).setId(sessionId);
		sessionMap.put(sessionId, session);
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		if(sessionId == null) {
			return null;
		}
		return sessionMap.get(sessionId.toString());
	}
}
